﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using HRM.BusinessLogic;
using HRM.Controller;

namespace HRM
{
    public partial class frmEmployee_NhapChucDanh : FormBase
    {
        bool _isSearch = false;

        EmployeeClient wcfEmployee;
        BranchClient wcfBranch;
        DepartmentClient wcfDepartment;
        RoleRightInfo listRole;
        MainServiceClient wcfMain;
        LabourContractClient wcfLC;
        LabourContractInfo _LCInfo;
        DetailClient _wcfDetail;
        int itemCount = 0;
        int pageSize = UIParamater.pageSize;
        int totalPage = 0;
        int currPage = 0;
        string _OrderBy = "";
        string _OrderDirection = "";
        int employeeID = 0;
        int department_ID;
        int branch_ID;
        int _EmpID = 0;
        int _LCID = 0;
        DataSet ds = null;

        public frmEmployee_NhapChucDanh()
        {
            InitializeComponent();
            //
            branch_ID = Program.intBranchID;
            //BranchCode = Program.strBranchCode;
            //
            wcfEmployee = Service.Employee();
            wcfBranch = Service.Branch();
            wcfDepartment = Service.Department();
            wcfMain = Service.MainService();
            wcfLC = Service.LabourContract();
            _wcfDetail = Service.Detail();
        }

        public override void Show_Form()
        {
            this.Show();
        }

        protected override void Init_Control()
        {
            //Hanlde nhập enter để nhảy ô tiếp theo
            this.KeyPreview = true; //event key của form xảy ra trc event của control :)
            this.KeyDown += FormGlobals.Dialog_KeyDown;
            
            //
            DateTextBoxShort dtbFrom = new DateTextBoxShort(mtxFromDate);
            DateTextBoxShort dtbTo = new DateTextBoxShort(mtxToDate);
            txtDateVal.Text = DateTime.Now.ToString("dd/MM/yyyy");
            //
            BuildVoucherGrid();
            UISetting.LoadTreeView3(ref tvBranch);

            
            FormGlobals.Control_SetRequired(mtxFromDate, mtxToDate, txtJob);
            //this.Textbox_SetKeyNextPreGroup(groupBox1);

            int counter;
            DataTable dtGrade = Position_Controller.Instance().Position_GetList(out counter, Program.strBranchCode, 0, 9999).Tables[0];
            new AutoCompleteTextBox_Handle(txtJob, dtGrade, "Position_Name");
            //
            LoadData();
            txtDateVal.ReadOnly = true;
            
            
        }

        private void BuildVoucherGrid()
        {
            dgvEmployeeList.Columns.Clear();
            dgvEmployeeList.ReadOnly = false;
            //Thêm cột Checkbox
            DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col.Name = "Check";
            col.HeaderText = "Chọn";
            col.Width = 50;
            col.ThreeState = false;
            col.TrueValue = true;
            col.FalseValue = false;
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            dgvEmployeeList.Columns.Add(col);
            col.Visible = true;
            //
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "RowNumber", UpdateUI.GetString("stt"), "C", 40, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Code", UpdateUI.GetString("maso"), "", 120, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_LastName", "hovatendem", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_FirstName", "ten", "", 1, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_FullName", UpdateUI.GetString("hovaten"), "", 150, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_CardNo", "", "C", 80, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Sex", "Giới tính", "C", 50, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Type", "Loại nhân viên", "C", 75, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_DateOfBirth", UpdateUI.GetString("ngaysinh"), "C", 100, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "EMPLOYEE_SIBOOKNO", "Số sổ BH", "C", 75, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_MedicalNo", "Số thẻ BHYT", "C", 75, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Department_Name", "Phòng ban", "", 130, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Position_Name", "Chức vụ", "", 110, true, true);

            UISetting.AddColumn(ref dgvEmployeeList, "Employee_IDCardNo", UpdateUI.GetString("CMTND"), "", 80, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_IDCardIssueDate", UpdateUI.GetString("ngaycap"), "", 80, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_IDCardIssueAuthority", UpdateUI.GetString("noicap"), "", 120, true, true);

            UISetting.AddColumn(ref dgvEmployeeList, "Employee_PlaceOfBirth", UpdateUI.GetString("noisinh"), "", 120, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Address", UpdateUI.GetString("diachi"), "", 150, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Phone", UpdateUI.GetString("dienthoai"), "", 100, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "MaritalStatus_Name", UpdateUI.GetString("tinhtranghonnhan"), "", 150, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Religion_Name", UpdateUI.GetString("tongiao"), "", 80, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Ethnic_Name", UpdateUI.GetString("dantoc"), "", 80, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_Culture", UpdateUI.GetString("trinhdovanhoa"), "", 100, true, true);


            UISetting.AddColumn(ref dgvEmployeeList, "Employee_BankAccountNo", UpdateUI.GetString("sotaikhoan"), "", 100, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_BankName", UpdateUI.GetString("nganhang"), "", 120, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_StartDate", UpdateUI.GetString("ngayvaocongty"), "", 120, true, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Employee_EndDate", UpdateUI.GetString("ngaythoiviec"), "", 120, true, true);
            //UISetting.AddColumn(ref dgvEmployeeList, "Branch_Name", "Chi nhánh", "", 100, false, true);
            UISetting.AddColumn(ref dgvEmployeeList, "Standard_Name", "Trình độ học vấn", "", 130, false, true);
        }

        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void LoadData()
        {
            //FormGlobals.App_ProgressShow(delegate()
            //{
            wcfEmployee = Service.Employee();
            //if (!_isSearch)
            //{
                ds = wcfEmployee.Employee_GetList(out itemCount, branch_ID, department_ID, UISetting.GetKeyWord(txtKeyWord.Text.Trim()), _OrderBy, _OrderDirection, currPage, pageSize);
                //datasetForExcel = wcfEmployee.Employee_GetList(out itemCount, branch_ID, department_ID, UISetting.GetKeyWord(txtKeyWord.Text.Trim()), _OrderBy, _OrderDirection, currPage, itemCount);
            //}
            //else
            //{
            //    ds = wcfEmployee.Employee_GetAdvSearch(out itemCount, branch_ID, _No, _CardNo, _IDCardNo, _FullName, _DOBFrom, _DOBTo, _POB, _Sex, _Standard_ID, _Position_ID, _Grade_ID, _ContractType_ID, _Specialist, _BasicSalaryFrom, _BasicSalaryTo, _LCNo, _LC_BeginDateFrom, _LC_BeginDateTo, _LC_FinishDateFrom, _LC_FinishDateTo, _Address, _Job, _BookNo, _MedicalNo, _StartDateFrom, _StartDateTo, _OrderBy, _OrderDirection, currPage, pageSize);
            //    //datasetForExcel = wcfEmployee.Employee_GetAdvSearch(out itemCount, branch_ID, _No, _CardNo, _IDCardNo, _FullName, _DOBFrom, _DOBTo, _POB, _Sex, _Standard_ID, _Position_ID, _Grade_ID, _ContractType_ID, _Specialist, _BasicSalaryFrom, _BasicSalaryTo, _LCNo, _LC_BeginDateFrom, _LC_BeginDateTo, _LC_FinishDateFrom, _LC_FinishDateTo, _Address, _Job, _BookNo, _MedicalNo, _StartDateFrom, _StartDateTo, _OrderBy, _OrderDirection, currPage, itemCount);
            //}
            int n = ds.Tables[0].Rows.Count;
            PageIndex();
            dgvEmployeeList.Rows.Clear();
            for (int i = 0; i < n; i++)
            {
                dgvEmployeeList.Rows.Insert(i, 1);
                dgvEmployeeList.Rows[i].Cells["Check"].Value = false;
                dgvEmployeeList.Columns["Employee_FullName"].Frozen = true;
                dgvEmployeeList.Rows[i].Cells["RowNumber"].Value = ds.Tables[0].Rows[i]["RowNumber"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_ID"].Value = ds.Tables[0].Rows[i]["Employee_ID"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_Code"].Value = ds.Tables[0].Rows[i]["Employee_Code"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_CardNo"].Value = ds.Tables[0].Rows[i]["Employee_CardNo"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_LastName"].Value = ds.Tables[0].Rows[i]["Employee_LastName"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_FirstName"].Value = ds.Tables[0].Rows[i]["Employee_FirstName"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_FullName"].Value = ds.Tables[0].Rows[i]["Employee_FullName"].ToString();
                dgvEmployeeList.Rows[i].Cells["EMPLOYEE_SIBOOKNO"].Value = ds.Tables[0].Rows[i]["EMPLOYEE_SIBOOKNO"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_MedicalNo"].Value = ds.Tables[0].Rows[i]["Employee_MedicalNo"];

                if (ds.Tables[0].Rows[i]["Employee_DateOfBirth"] != DBNull.Value)
                    dgvEmployeeList.Rows[i].Cells["Employee_DateOfBirth"].Value = Convert.ToDateTime(ds.Tables[0].Rows[i]["Employee_DateOfBirth"]).ToString("dd/MM/yyyy");
                else
                    dgvEmployeeList.Rows[i].Cells["Employee_DateOfBirth"].Value = "";
                dgvEmployeeList.Rows[i].Cells["Employee_PlaceOfBirth"].Value = ds.Tables[0].Rows[i]["Employee_PlaceOfBirth"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_Address"].Value = ds.Tables[0].Rows[i]["Employee_Address"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_Phone"].Value = ds.Tables[0].Rows[i]["Employee_Phone"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_Culture"].Value = ds.Tables[0].Rows[i]["Employee_Culture"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_Sex"].Value = ds.Tables[0].Rows[i]["Employee_Sex"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_Type"].Value = ds.Tables[0].Rows[i]["Employee_Type"].ToString();
                dgvEmployeeList.Rows[i].Cells["MaritalStatus_Name"].Value = ds.Tables[0].Rows[i]["MaritalStatus_Name"].ToString();
                dgvEmployeeList.Rows[i].Cells["Religion_Name"].Value = ds.Tables[0].Rows[i]["Religion_Name"].ToString();
                dgvEmployeeList.Rows[i].Cells["Ethnic_Name"].Value = ds.Tables[0].Rows[i]["Ethnic_Name"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_IDCardNo"].Value = ds.Tables[0].Rows[i]["Employee_IDCardNo"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_IDCardIssueDate"].Value
                    = ds.Tables[0].Rows[i]["Employee_IDCardIssueDate"] == DBNull.Value ? ""
                    : Convert.ToDateTime(ds.Tables[0].Rows[i]["Employee_IDCardIssueDate"]).ToString("dd/MM/yyyy");
                dgvEmployeeList.Rows[i].Cells["Employee_IDCardIssueAuthority"].Value = ds.Tables[0].Rows[i]["Employee_IDCardIssueAuthority"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_BankAccountNo"].Value = ds.Tables[0].Rows[i]["Employee_BankAccountNo"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_BankName"].Value = ds.Tables[0].Rows[i]["Employee_BankName"].ToString();
                dgvEmployeeList.Rows[i].Cells["Employee_StartDate"].Value
                    = ds.Tables[0].Rows[i]["Employee_StartDate"] == DBNull.Value ? ""
                    : Convert.ToDateTime(ds.Tables[0].Rows[i]["Employee_StartDate"]).ToString("dd/MM/yyyy");
                dgvEmployeeList.Rows[i].Cells["Employee_EndDate"].Value
                    = ds.Tables[0].Rows[i]["Employee_EndDate"] == DBNull.Value ? ""
                    : Convert.ToDateTime(ds.Tables[0].Rows[i]["Employee_EndDate"]).ToString("dd/MM/yyyy");

                dgvEmployeeList.Rows[i].Cells["Position_Name"].Value = ds.Tables[0].Rows[i]["Position_Name"].ToString();
                //dgvEmployeeList.Rows[i].Cells["Branch_Name"].Value = ds.Tables[0].Rows[i]["Branch_Name"].ToString();
                dgvEmployeeList.Rows[i].Cells["Department_Name"].Value = ds.Tables[0].Rows[i]["Department_Name"].ToString();
                dgvEmployeeList.Rows[i].Cells["Standard_Name"].Value = ds.Tables[0].Rows[i]["Standard_Name"].ToString();
            }
            //}, "Đang tải danh sách");
        }

        string _selectedID = "";
        string _sSiBookNo ="";
        private void GetSelectedID()
        {
            dgvEmployeeList.EndEdit();
            foreach (DataGridViewRow row in dgvEmployeeList.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value))
                {
                    if (!_selectedID.Contains("," + row.Cells["Employee_ID"].Value.ToString() + ","))
                        _selectedID += row.Cells["Employee_ID"].Value.ToString() + ",";
                    //
                    if (!_sSiBookNo.Contains("," + row.Cells["Employee_SiBookNo"].Value.ToString() + ","))
                        _sSiBookNo += row.Cells["Employee_SiBookNo"].Value.ToString() + ",";
                }
                else
                {
                    string sOld = "," + row.Cells["Employee_ID"].Value.ToString() + ",";
                    if (_selectedID.Contains(sOld))
                        _selectedID = _selectedID.Replace(sOld, ",");
                    //
                    sOld = "," + row.Cells["Employee_SiBookNo"].Value.ToString() + ",";
                    if (_sSiBookNo.Contains(sOld))
                        _sSiBookNo = _sSiBookNo.Replace(sOld, ",");
                }
            }
        }


        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (totalPage > 0 && currPage < totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage > 0)
                currPage--;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (totalPage != 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            txtKeyWord.Text = "";
            _isSearch = false;
            DataTable dt = new DataTable();
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                    branch_ID = 0;
                else
                    branch_ID = Program.intBranchID;
                department_ID = 0;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                branch_ID = Convert.ToInt32(e.Node.Tag);
                department_ID = 0;
                currPage = 0;
                LoadData();
            }
            else if (e.Node.Level >= 2)
            {
                department_ID = Convert.ToInt32(e.Node.Tag);
                branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                currPage = 0;
                LoadData();
            }
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnFind_Click(null, null);
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            currPage = 0;
            _isSearch = false;
            LoadData();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            //
            if (!CheckValid())
            {
                return;
            }
            if (_selectedID.Replace(",","").Trim().Length > 0)
            {
                if (FormGlobals.Message_Confirm("Bạn có chắc muốn điều chỉnh chức danh của danh sách những người đã chọn"))
                {
                    //MessageBox.Show("Điều chỉnh");
                    
                    DateTime fromDate = DateTime.ParseExact(mtxFromDate.Text, "MM/yyyy", null);
                    DateTime toDate = DateTime.ParseExact(mtxToDate.Text, "MM/yyyy", null);

                    string [] arrSoSoBHXH = _sSiBookNo.Split(new string[] { "," }, StringSplitOptions.None);
                    foreach (string siBookNo in arrSoSoBHXH)
                    {
                        Employee_Controller.Instance().Employee_UpdateChucDanh(0, Program.strBranchCode, siBookNo, fromDate, toDate, txtJob.Text);
                    }
                    //
                    MessageBox.Show("Lưu thành công");
                    //reload
                    mtxFromDate.Text = mtxToDate.Text = txtJob.Text = "";
                    btnFind_Click(null, null);
                }
            }
        }

        private bool CheckValid()
        {
            if (!CheckTextValid.IsDateTime(mtxFromDate.Text, "MM/yyyy"))
            {
                mtxFromDate.Focus();
                MessageBox.Show(UpdateUI.GetString("ngaybatdaukhonghople"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (!CheckTextValid.IsDateTime(mtxToDate.Text, "MM/yyyy"))
            {
                mtxToDate.Focus();
                MessageBox.Show(UpdateUI.GetString("ngayketthuckhonghople"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (DateTime.Compare(UISetting.GetDate(mtxFromDate.Text), UISetting.GetDate(mtxToDate.Text)) > 0)
            {
                mtxFromDate.Focus();
                MessageBox.Show(UpdateUI.GetString("ngayketthucphaimuonhonngaybatdau"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            DateTime maxPS = SalaryFund_Controller.Instance().GetMaxKyPS(Program.strBranchCode);
            if (UISetting.GetDate(mtxToDate.Text) > maxPS)
            {
                mtxToDate.Focus();
                MessageBox.Show("Đến tháng không được vượt quá kỳ phát sinh bảo hiểm: " + maxPS.ToString("MM/yyyy") , UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            if (String.IsNullOrEmpty(txtJob.Text))
            {
                MessageBox.Show("Bạn cần nhập chức danh/nghề nghiệp");
                txtJob.SetFocus_SelectAll();
                return false;
            }

            if (_selectedID.Replace(",", "").Trim().Length == 0)
            {
                MessageBox.Show("Bạn cần chọn lao động để thực hiện thao tác");
                return false;
            }
            return true;
        }

        private void chkAll_Checked_Changed(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvEmployeeList.Rows.Count; i++)
            {
                dgvEmployeeList.Rows[i].Cells["Check"].Value = chkAll.Checked;
            }
        }
    }
}
